Flash Article

Creating Movie Clip Subclasses in ActionScript 2.0


Table of Contents

  1. Introduction
  2. Classes and Objects, Symbols and Clips
  3. A Short History of Movie Clip Behaviors
  4. Tutorial 1: Using a Movie Clip Subclass to Make a Bouncing Ball Animation
  5. Tutorial 2: Creating a More Extensive Grab-and-Match Puzzle

Tutorial 1: Using a Movie Clip Subclass to Make a Bouncing Ball Animation

This tutorial shows you how to create an animation (displayed below) that contains multiple instances of one bouncing-ball movie clip.

Each instance of the movie clip contains a different message and has a different opacity; one is even scaled larger than the others. Despite these variations, you can see that the movie clip instances still exhibit the same behavior. They each appear in a random place, move off in a random direction, and correctly bounce off the edge of the Stage.

Before you begin the tutorial, you should have an overall view of the basic steps I will cover:

  1. Create a movie clip named Ball.
  2. Set the linkage properties of the Ball clip to export it for use by ActionScript and associate it with the ActionScript 2.0 Ball class
  3. .
  4. Create an ActionScript class named Ball in a file named Ball.as that extends the MovieClip class.
  5. Write a constructor function to initialize each clip when it is created and an onEnterFrame event handler method to set the new position for the ball when a new frame is about to appear.
  6. In the first frame of the main Timeline of the movie use the attachMovie function to add as many instances of the Ball movie clip to the Stage as you want. Use the initObject parameter to give each Ball movie clip unique property values like size, message, and opacity.

Step 1: Create the Movie Clip

Create a new Flash movie and save it in a new directory. Choose Insert > New Symbol in the main menu. In the Create New Symbol dialog box, name the movie clip Ball. In the Behavior section, select the Movie Clip option and click OK. To follow this tutorial, draw a ball shape or your own graphic. The graphic must be centered on the registration point. In this example, the graphic is composed of layers of simple circle drawings. The top two are semitransparent and contain a radial gradient fill; the bottom layer contains a simple circle with a flat color.

Next add a text field on top of the movie clip graphic (see Figure 1). I happened to use the text letter A. With the text field selected, verify on the Property inspector that Text Type is set to Dynamic Text. In the Var text box, type msg. This ties the text field to a variable.

Note: The initial text in the text field is just for sizing and will not appear when each instance of the Ball movie clip is attached to the movie. Also, the height and width of the text field is less than the height or width of the ball.

Creating the Ball movie clip.

Figure 1. Creating the Ball movie clip.

Step 2: Set the Linkage Properties of the Ball Clip

After creating the visual parts of the movie clip, associate it with the ActionScript 2.0 Ball class by right-clicking (Windows) or Command-clicking (Macintosh) the movie clip's name in the library. In the context menu, select Linkage. This opens the Linkage Properties dialog box (see Figure 2). Click the Export for ActionScript option and type Ball in the AS 2.0 Class field. Make sure Identifier is also named Ball and that the Export in First Frame option is also selected. Click OK.

Associating the Ball movie clip with the Ball class.

Figure 2. Associating the Ball movie clip with the Ball class.

Step 3: Creating the Ball Class

Now that you've properly identified the movie clip and associated it with an ActionScript 2.0 class it's time to create the Ball class. Save the Ball class in a separate text file named Ball.as. You can use any text editor to create and edit the file or else you can use Macromedia Flash MX 2004 or Macromedia Flash MX Professional 2004. If you use either edition of Flash, select File > New > ActionScript File. When you see the untitled script editing pane choose File > Save As and save the empty file in the same directory as your FLA file. Make sure you name the script file Ball.as.

Now define the ActionScript Ball class. Type the following into the file and save it again:

dynamic class Ball extends MovieClip {

}

This short bit of code defines a new class that is a subclass of the MovieClip class. Making it a MovieClip subclass means that it can manipulate all the properties of any Ball movie clip and also define event handling methods for all the events a movie clip receives. Reading from left to right, here is what the words in this short class definition mean:

  • dynamic: Indicates that each Ball object can have new methods and properties created for it at any time. They do not have to be defined in the class definition. Movie clips are dynamic and therefore so are classes that subclass (or extend) them.
  • class: Says that you are defining a class of objects that will all get their behavior from this class definition.
  • Ball: The name of the class.
  • extends: If the class is based on another class, and therefore inherits all the properties and methods of the base class, the extends keyword is used.
  • MovieClip: The name of the class being extended.

Step 4: Coding the Ball Class

So far, the class definition in your ActionScript file doesn't do anything. You need to have your class do two things: It needs to initialize itself by doing things like choosing an initial place to appear on the Stage and it needs to respond to enterFrame events so that it can move itself to its next position on the Stage before the next frame of the movie appears:

dynamic class Ball extends MovieClip {

   function Ball() {
   }
   
   function onEnterFrame() {
   }

}

Initializing the Class with a Constructor Function: Within the Ball class definition a function named Ball is also defined. Because the function has the same name as the class it will be called each time a Ball object is created. The function is therefore called a constructor function and it is normally used to initialize the object before it is used.

Event Handlers: Every movie clip subclass inherits the ability to define methods to receive (or handle) movie clip events. The method names are named after the events. In this example, an onEnterFrame method is defined and called just before the clip appears in each new frame of the movie. It plays the same role as manually attaching an onClipEvent(enterFrame) handler to a movie clip on the Stage.

The Ball Constructor Function in Detail: The Ball constructor function does three things:

  • Determine how far in the x and y axis the clip's registration point can travel before it has to bounce back into the Stage
  • Position the clip at a random location within the safe travel zone for the clip's registration point
  • Generate a random amount to move the clip along the x and y axis between frames (x velocity and y velocity)

Here is the actual code for the Ball constructor function:

function Ball() {
   // Calculate the limits of travel for this clip's registration point.
   xMin = _width/2;
   yMin = _height/2;
   xMax = Stage.width  - xMin;
   yMax = Stage.height - yMin;
   
   // Determine the random starting position within the Stage for this clip.    
   _x = Math.floor(Math.random()*(Stage.width  - _width))  + xMin;
   _y = Math.floor(Math.random()*(Stage.height - _height)) + yMin;
   
   // Generate random x and y velocities for each instance of this clip.
   xVel = Math.floor(Math.random() * 25) - 10;
   yVel = Math.floor(Math.random() * 25) - 10;
}

Two things are worth noting about how this particular constructor function works. One is that, unlike in ActionScript 1.0, it uses the _width, _height, _x, and _y properties of the movie clip without having to add the keyword this.

Instead of:

xMin = this._width/2;

You can just write:

xMin = _width/2;

This is a feature of ActionScript 2.0. Also this is not required to assign values to other properties of the object. In this code, xMin, xMax, yMin, yMax, xVel, and yVel are all properties of each Ball object. However, to make them properties you either need to declare them within the class definition or return to using the this keyword. Since you have to declare object properties you might as well take advantage of ActionScript 2.0's strong typing feature and declare what type of value each variable may contain. This snippet of code shows the declarations, and where to put them, within the Ball class definition:

dynamic class Ball extends MovieClip {

   // Travel limits for the movie clip's registration point.
   var xMin:Number, yMin:Number, xMax:Number, yMax:Number;
   // Velocity in x and y for the movie clip.
   var xVel:Number, yVel:Number;
   // Variable set in attachMovie and used by the text field.
   var msg:String;

   function Ball() {
   }
   
   function onEnterFrame() {
   }
}

The onEnterFrame Method in Detail: The onEnterFrame method calculates the next position for the movie clip and checks to make sure it is within the movie clip's travel limits. If it is not, the position of the registration point is recalculated as though it has just bounced off the edge of the Stage. The x and y position of the registration point are calculated separately:

function onEnterFrame() {
   /// Get the x and y positions for the next frame.
   var nextX = xVel + _x;
   var nextY = yVel + _y;
   
   // Make sure the registration point is within limits.
   if (nextX > xMax) {
      // Change direction by changing the sign of xVel.
      xVel = xVel * -1;
      // Bring clip back by the amount it has overshot its limit.
      nextX = this.xMax - (nextX - xMax);
   } else if (nextX < xMin) {
      xVel = xVel * -1;
      nextX = xMin + (xMin - nextX);
   }
   if (nextY > yMax) {
      yVel = yVel * -1;
      nextY = yMax - (nextY - yMax);
   } else if (nextY < yMin) {
      yVel = yVel * -1;
      nextY = yMin + (yMin - nextY);
   }
   
   // Now that we are sure the position in nextX and nextY are correct, 
   // set the position for the next frame.
   _x = nextX;
   _y = nextY;
}

Finally, here is the entire code in the Ball.as file, complete with comments:

/**
 * The Ball class extends the dynamic MovieClip class and is therefore also
 * dynamic. The Ball class assumes a MovieClip in the library is associated with
 * this class. 
 */
dynamic class Ball extends MovieClip {
   // Travel limits for the movie clip's registration point.
   var xMin:Number, yMin:Number, xMax:Number, yMax:Number;
   // Velocity in x and y for the movie clip.
   var xVel:Number, yVel:Number;
   // Variable set in attachMovie and used by the text field.
   var msg:String;

   /** 
    * The Ball constructor function calculates the bounding rectangle
    * within which this clip's registration point is allowed to travel.
    * The clip's registration point is assumed to be in the center of the 
    * clip but the height and width of the clip do not have to be the same.
    * Therefore the bounding rectangle is calculated for each clip when
    * each clip's constructor is called. 
    * The Stage object provides Stage.width and Stage.height.
    * A random starting position and random velocity are also determined.
    */
   function Ball() {
      // Calculate the limits of travel for this clip's registration point.
      xMin = _width/2;
      yMin = _height/2;
      xMax = Stage.width  - xMin;
      yMax = Stage.height - yMin;
      
      // Determine the random starting position within the Stage for this clip.    
      _x = Math.floor(Math.random()*(Stage.width  - _width))  + xMin;
      _y = Math.floor(Math.random()*(Stage.height - _height)) + yMin;
      
      // Generate random x and y velocities for each instance of this clip.
      xVel = Math.floor(Math.random() * 25) - 10;
      yVel = Math.floor(Math.random() * 25) - 10;
   }
   
   /**
    * The onEnterFrame method calculates the next position for the movie clip
    * and then checks to make sure it is within the movie clip's travel limits.
    * If it is not the position of registration point is recalculated as though
    * it has just bounced off the edge of the stage. The x and y position of the
    * registration point are calculated separately.
    */
   function onEnterFrame() {
      /// Get the x and y positions for the next frame.
      var nextX = xVel + _x;
      var nextY = yVel + _y;
      
      // Make sure the registration point is within limits.
      if (nextX > xMax) {
         // Change direction by changing the sign of xVel.
         xVel = xVel * -1;
         // Bring clip back by the amount it has overshot its limit.
         nextX = xMax - (nextX - xMax);
      } else if (nextX < xMin) {
         xVel = xVel * -1;
         nextX = xMin + (xMin - nextX);
      }
      if (nextY > yMax) {
         yVel = yVel * -1;
         nextY = yMax - (nextY - yMax);
      } else if (nextY < yMin) {
         yVel = yVel * -1;
         nextY = yMin + (yMin - nextY);
      }
      
      // Now that we are sure the position in nextX and nextY are correct, 
      // set the position for the next frame.
      _x = nextX;
      _y = nextY;
   }
}

Step 5: Attaching Instances of the Movie Clip to the Stage

To attach a movie clip to the Stage and initialize it in Macromedia Flash 5 you write code like this:

attachMovie("Ball", "b0", 100);
mc = eval("b0");
mc.msg = "Hi";
mc._alpha = 50;

The first line attaches the movie clip in the library with the linkage identifier "Ball" to the Stage, gives it an instance name of "b0", and sets its stacking level at 100. The next line uses the eval() function to make the mc variable a reference to the "b0" instance of the clip. The last two lines use the reference in mc to set the initial properties of the movie clip.

You can still do the same thing in Flash MX and Flash MX 2004 even though the eval() function is no longer necessary:

mc = attachMovie("Ball", "b0", 100);
mc.msg = "Hi";
mc._alpha = 50;

However, this doesn't let you feed information to your constructor function. That's because the constructor function is called when attachMovie() is called. The msg and _alpha properties of the object will be changed after the constructor is called. To pass information to the constructor function you need to use the initObject parameter of the attachMovie() method.

Here's a one-line example that does the same thing as the three or four statements above:

attachMovie("Ball", 'b0', 100, {msg: 'Hi', _alpha: 50});

This use of attachMovie() is the same as the first line in the previous Flash 5 example, except that an additional parameter became available with Flash MX in the attachMovie() function. In the documentation, this is called an initObject, which contains initial values that populate the object before the constructor function is called. (Anyone familiar with object-oriented programming can think of this as similar to providing parameters to a movie clip constructor function.) There are other ways to write this but the curly brackets are probably the simplest. The following expression creates an object with two properties: msg and _alpha. The values for these properties follow the colon after each property's name:

{msg: 'Hi', _alpha: 50}

You can place the following code on the first frame of the main Timeline of the movie. It creates three instances of the Ball movie clip, each of which contains a different message and has a different _alpha value. The last one is twice as large as the previous two because the _xscale and _yscale values are also set:

attachMovie("Ball", 'b0', 102, {msg: 'Hi', _alpha: 50});
attachMovie("Ball", 'b1', 101, {msg: 'Bye', _alpha: 80});
attachMovie("Ball", 'b2', 100, {msg: 'Big', _alpha: 100, 
                                _xscale: 200, _yscale: 200});

Note that in the third instance, the size of the movie clip will be different; this is reflected in different _width and _height values in the constructor function.

If you don't want to use an initObject as shown here and prefer to use this type of code instead:

mc = attachMovie("Ball", "b0", 100);
mc.msg = "Hi";
mc._alpha = 50;

Create an onLoad() method and move your initialization code from your constructor function into your onLoad() method. The onLoad() method will be called after the msg and _alpha properties are set.

In summary, you can associate movie clip symbols with ActionScript 2 classes. When a clip is created an ActionScript object is created and its constructor is called. When movie clip events occur, the ActionScript object associated with the instance of the movie clip symbol responds. Using ActionScript 2.0, you can write classes more easily and safely (with strong typing) than you could in ActionScript 1.0. It's also easier to write larger and more complex applications. Whether you use ActionScript 1.0 or 2.0, associating a class with a symbol in the library is the best way to give a movie clip symbol predefined behaviors.

In the next tutorial, you pick up the pace to create a more complicated grab-and-match-the-shapes game.